package com.study.springmvc.config;

import com.study.springmvc.controller.ThreadLocalContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadPoolConfig {

    @Bean(name = "taskExecutor-1")
    public ThreadPoolExecutor taskExecutor() {
        return new CustomThreadPoolExecutor<>(new CustomThreadPoolExecutor.ThreadLocalContext<String>() {
            @Override
            public String getContext() {
                return ThreadLocalContext.getTraceId();
            }

            @Override
            public void setContext(String context) {
                ThreadLocalContext.setTraceId(context);
            }
        }, 5, 10, 300, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), new CustomThreadFactory("monitor-async-thread"), new ThreadPoolExecutor.CallerRunsPolicy());
    }

    @Bean(name = "taskExecutor-2")
    public ThreadPoolExecutor taskExecutor2() {
        return new CustomThreadPoolExecutor<>(new CustomThreadPoolExecutor.ThreadLocalContext<String>() {
            @Override
            public String getContext() {
                return ThreadLocalContext.getTraceId();
            }

            @Override
            public void setContext(String context) {
                ThreadLocalContext.setTraceId(context);
            }
        }, 5, 10, 300, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100), new CustomThreadFactory("monitor-future-thread"), new ThreadPoolExecutor.CallerRunsPolicy());
    }
}
